package com.google.code.study.webview;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Program extends Activity  
{
    public static final String KEY_URL = "keyUrl";
    private WebView            mWebView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate( Bundle _savedInstanceState )
    {
        super.onCreate( _savedInstanceState );
        requestWindowFeature( Window.FEATURE_INDETERMINATE_PROGRESS );
        requestWindowFeature( Window.FEATURE_PROGRESS );
        setContentView( R.layout.main );
        mWebView = (WebView) findViewById( R.id.wv_world );
        mWebView.setWebViewClient( new WebViewClient()
        {
            public void onPageStarted( WebView _view, String _url, android.graphics.Bitmap _favicon )
            {
                setTitle( _url );
            };

            public void onPageFinished( WebView _view, String _url )
            {
                setTitle( "DONE!" );
            };
        } );
        mWebView.setWebChromeClient( new WebChromeClient()
        {
            public void onProgressChanged( WebView _view, int _progress )
            {
                setProgress( _progress * 100 );
                if( _progress == 100 )
                {
                    setProgressBarIndeterminateVisibility( false );
                    setProgressBarVisibility( false );
                }
            }
        } );
        loadPage( getIntent() );
    }

    private void loadPage( Intent _i )
    {
        if( _i != null )
        {
            String url = _i.getStringExtra( KEY_URL );
            mWebView.loadUrl( url );
        }
        else
        {
            Toast.makeText( this, "NULL intent", Toast.LENGTH_LONG ).show();
        }
    }

    @Override
    protected void onNewIntent( Intent _intent )
    {
        super.onNewIntent( _intent );
        loadPage( _intent );
        Toast.makeText( this, "NEW intent:" + _intent.getStringExtra( KEY_URL ), Toast.LENGTH_LONG ).show();
    }

    private void startActivty( String _pageUrl, int _flag )
    {
        Intent intent = new Intent( this, Program.class );
        intent.putExtra( KEY_URL, _pageUrl );
        intent.setFlags( _flag );
        startActivity( intent );
    }

    public void startByTopAndClear( View _v )
    {
        startActivty( "http://www.yahoo.de", Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP );
    }

    public void startByClear( View _v )
    {
        startActivty( "http://www.spiegel.de", Intent.FLAG_ACTIVITY_CLEAR_TOP );
    }
}
